from flask import Blueprint, request, jsonify
from flaskapp.entity.Collect import Collect
from flaskapp.util.Redprint import Redprint
from flaskapp.entity.House import House
from flaskapp.util.Sqlalchemy import db

api = Redprint('collect')

@api.route('/list', methods=['GET'])
def get_collect_list():
    try:
        user_id = request.args.get('user_id', type=int)
        if not user_id:
            return jsonify({'status': 400, 'msg': '缺少用户ID'})

        # 获取用户收藏的房源列表，只获取is_collected为True的记录
        collects = db.session.query(Collect, House).join(
            House, Collect.house_id == House.house_id
        ).filter(
            Collect.user_id == user_id,
            Collect.is_collected == True
        ).all()

        # 组装返回数据
        houses = [{
            **house.to_dict(),
            'collect_id': collect.collect_id,
            'collected_at': collect.created_at.strftime('%Y-%m-%d %H:%M:%S')
        } for collect, house in collects]
        print(houses)
        return jsonify({
            'status': 200,
            'msg': '获取成功',
            'data': houses
        })

    except Exception as e:
        return jsonify({'status': 500, 'msg': str(e)})

@api.route('/add', methods=['POST'])
def add_collect():
    try:
        data = request.get_json()
        user_id = data.get('user_id')
        house_id = data.get('house_id')

        if not all([user_id, house_id]):
            return jsonify({'status': 400, 'msg': '缺少必要参数'})

        # 检查是否已存在收藏记录
        existing_collect = Collect.query.filter_by(
            user_id=user_id,
            house_id=house_id
        ).first()
        print(existing_collect)
        if existing_collect:
            if existing_collect.is_collected:
                return jsonify({'status': 400, 'msg': '已经收藏过了'})
            # 如果之前取消过收藏，则重新收藏
            existing_collect.is_collected = True
            db.session.commit()
        else:
            # 创建新的收藏记录
            new_collect = Collect(
                user_id=user_id,
                house_id=house_id
            )
            print(new_collect)
            db.session.add(new_collect)
            db.session.commit()

        return jsonify({'status': 200, 'msg': '收藏成功'})

    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 500, 'msg': str(e)})

@api.route('/cancel', methods=['POST'])
def cancel_collect():
    try:
        data = request.get_json()
        user_id = data.get('user_id')
        house_id = data.get('house_id')

        if not all([user_id, house_id]):
            return jsonify({'status': 400, 'msg': '缺少必要参数'})

        collect = Collect.query.filter_by(
            user_id=user_id,
            house_id=house_id,
            is_collected=True
        ).first()

        if not collect:
            return jsonify({'status': 400, 'msg': '未找到收藏记录'})

        collect.is_collected = False
        db.session.commit()

        return jsonify({'status': 200, 'msg': '取消收藏成功'})

    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 500, 'msg': str(e)})

@api.route('/check', methods=['GET'])
def check_collect_status():
    try:
        user_id = request.args.get('user_id', type=int)
        house_id = request.args.get('house_id', type=int)

        if not all([user_id, house_id]):
            return jsonify({'status': 400, 'msg': '缺少必要参数'})

        collect = Collect.query.filter_by(
            user_id=user_id,
            house_id=house_id,
            is_collected=True
        ).first()

        return jsonify({
            'status': 200,
            'msg': '查询成功',
            'is_collected': bool(collect)
        })

    except Exception as e:
        return jsonify({'status': 500, 'msg': str(e)})